<?php
/**
 * Created by phpstorm.
 * User: WML
 * Date: 2019/9/10 0010
 * Time: 09:55
 */

namespace app\chat\controller;

use app\model\Users;
use think\Controller;
use think\Db;
use think\facade\Session;

class User extends Allow
{
    //用户列表
    public function chatList()
    {
        $lineUser = Session::get('lineUser');
        $currentUser = Users::get(Session::get('chat_user_id'));
        $users = db("users")->select();
        $this->assign('users',$users);
        $this->assign('lineUser',$lineUser);
        $this->assign('total',count($users));
        $this->assign('currentUser',$currentUser);
        $this->assign('sess_user_id',Session::get('chat_user_id'));
        return view("chat_list");
    }

    //聊天页面
    public function chatDetail(){
        $receive_id = input("id");
        $send_id = Session::get('chat_user_id');
        $send_data = Users::get($send_id);
        $receive_data = Users::get($receive_id);

        $this->assign([
            'send_data' => $send_data,
            'receive_data' => $receive_data,
            'receive_id' => $receive_id,
            'send_id' => $send_id,
            'date_time' => date("Y-m-d H:i:s",intval(time()))
        ]);
        return view("chat_detail");
    }

    //持久化保存数据
    public function saveChatData(){
        $param = request()->param();
        $data = [
            'send_id' => $param['send_id'],
            'receive_id' => $param['receive_id'],
            'content' => $param['text'],
            'time' => date("Y-m-d H:i:s")
        ];
        db("chat_content")->insert($data);
    }

    //查询出来最近的15条数据
    public function chatRecord(){
        $data = request()->param();
        $data = db("chat_content")
            ->where("(send_id=:send_id and receive_id=:receive_id) || (send_id=:receive_id1 and receive_id=:send_id1)")
            ->bind(['send_id' => $data['send_id'],'receive_id' => $data['receive_id'],'receive_id1' => $data['receive_id'],'send_id1' => $data['send_id']])
            ->order("id desc")
            ->limit(9)
            ->select();
//        $res = Db::table("chat_content")->getLastSql();
        return $data;
    }

    //查询出来最后一条数据
    public function findLast(){
        $data = request()->param();
        $data = db("chat_content")
            ->where("(send_id=:send_id and receive_id=:receive_id) || (send_id=:receive_id1 and receive_id=:send_id1)")
            ->bind(['send_id' => $data['send_id'],'receive_id' => $data['receive_id'],'receive_id1' => $data['receive_id'],'send_id1' => $data['send_id']])
            ->order("id desc")
            ->find();
        return $data;
    }
}